package com.gali.mall.service.impl;

import com.gali.mall.common.Const;
import com.gali.mall.exception.GaLiException;
import com.gali.mall.exception.GaLiExceptionEnum;
import com.gali.mall.model.dao.ProductMapper;
import com.gali.mall.model.pojo.Product;
import com.gali.mall.model.query.ProductListQuery;
import com.gali.mall.model.vo.CategoryVO;
import com.gali.mall.request.productReq.ProductListReq;
import com.gali.mall.service.CategoryService;
import com.gali.mall.service.ProductService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author gali
 * @date 2022/4/11 20:08
 */
@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private CategoryService categoryService;
    /**
     * 增加商品
     *
     * @param product
     * @return
     */
    @Override
    public boolean addProduct(Product product) {
        Product product1 = productMapper.checkInName(product.getName());
        if (product1!=null){
            throw new GaLiException(GaLiExceptionEnum.NAME_EXITS);
        }
        return productMapper.insertSelective(product)>0;
    }

    /**
     * 删除商品
     *
     * @param id
     * @return
     */
    @Override
    public boolean removeProduct(Integer id) {
        return productMapper.deleteByPrimaryKey(id)>0;
    }

    /**
     * 更新商品
     *
     * @param product
     * @return
     */
    @Override
    public boolean reviseProduct(Product product) {
        Product product1 = productMapper.checkInName(product.getName());
        if (product1!=null&&!product1.getId().equals(product.getId())){
            throw new GaLiException(GaLiExceptionEnum.NAME_EXITS);
        }
        return productMapper.updateByPrimaryKeySelective(product)>0;
    }

    /**
     * 查询全部商品
     *
     * @return
     */
    @Override
    public PageInfo findAll(Integer pageNumber, Integer pageSize) {
        PageHelper.startPage(pageNumber,pageSize);
        List<Product> list =productMapper.selectAll();
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }

    /**
     * 根据id查询商品
     *
     * @param id
     * @return
     */
    @Override
    public Product findById(Integer id) {
        Product product = productMapper.selectByPrimaryKey(id);
        if (product==null){
            throw  new GaLiException(GaLiExceptionEnum.NAME_NOT_EXIST);
        }
        return productMapper.selectByPrimaryKey(id);
    }

    /**
     * 商品名模糊查询
     *
     * @param name
     * @return
     */
    @Override
    public List<Product> findFromName(String name) {
        return productMapper.selectFromName(name);
    }

    @Override
    public boolean updates(Integer[] ids, Integer status) {
        return productMapper.updateBrachStatus(ids,status)>0;
    }

    /**
     * 商品列表（模糊查询）
     *
     * @param productListReq
     * @return
     */
    @Override
    public PageInfo list(ProductListReq productListReq) {
        ProductListQuery productListQuery = new ProductListQuery();
//搜索处理
        if(!StringUtils.isEmpty(productListReq.getKeyword())){
//判空处理，使用模糊查询
            String keyword = new StringBuilder().append("%").append(productListReq.getKeyword()).append("%").toString();
            productListQuery.setKeyword(keyword);
        }
//目录处理：如果查某个目录下的商品，不仅是需要查出该目录下的，还要把所有子目录的所有商品都查出来，所以要拿到一个目录id的List
        if(productListReq.getCategoryId()!=null){
//获取此目录的子目录，重构categoryService.listForCustomer方法，增加入参，
//修改CategoryController.listCategoryForCustomer方法，设置parentId参数为0
            List<CategoryVO> categoryVOList =
                    categoryService.listForCustomer(productListReq.getCategoryId());
            ArrayList<Integer> categoryIds = new ArrayList<>();
            categoryIds.add(productListReq.getCategoryId());
            getCategoryIds(categoryVOList, categoryIds);
            productListQuery.setCategoryIds(categoryIds);
        }
//排序处理，不能根据前端的排序参数来处理，不安全
        String orderBy = productListReq.getOrderBy();
//定义排序规则接口Constant.ProductListOrderBy.PRICE_ASC_DESC
        if (Const.ProductListOrderBy.PRICE_ASC_DESC.contains(orderBy)) {
//获取的前端排序规则支持接口中的排序规则，使用规则进行构建分页对象
            PageHelper.startPage(productListReq.getPageNum(), productListReq.getPageSize(), orderBy);
        } else {
//不支持接口中的规则，不进行排序
            PageHelper.startPage(productListReq.getPageNum(), productListReq.getPageSize());
        }
        List<Product> productList = productMapper.selectList(productListQuery);
        PageInfo pageInfo = new PageInfo(productList);
        return pageInfo;
    }
    //递归获取子目录信息
    private void getCategoryIds(List<CategoryVO> categoryVOList, ArrayList<Integer> categoryIds) {
        for (int i = 0; i < categoryVOList.size(); i++) {
            CategoryVO categoryVO = categoryVOList.get(i);
            if (categoryVO != null) {
                categoryIds.add(categoryVO.getId());
                getCategoryIds(categoryVO.getCategoryVoList(), categoryIds);
            }
        }
    }

}
